package genericity;

import java.util.Iterator;

interface Generator<T> {
    T next();
}

class FibonacciGenerator implements Generator<Integer> {

    protected int count = 0;

    private int fib(int n) {
        if(n == 0 || n == 1)
            return 1;
        return fib(n - 1) + fib(n - 2);
    }

    @Override
    public Integer next() {
        return fib(count ++);
    }
}

class IterableFibonacciGenerator extends FibonacciGenerator implements Iterable<Integer> {

    private int n;

    public IterableFibonacciGenerator(int n) {
        this.n = n;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            @Override
            public boolean hasNext() {
                return count < n;
            }

            @Override
            public Integer next() {
                return IterableFibonacciGenerator.this.next();
            }
        };
    }
}

/**
 * 斐波那契数列 生成器
 */
public class FibonacciDemo {
    public static void main(String[] args) {
        FibonacciGenerator generator = new FibonacciGenerator();
        for (int i = 0; i < 10; i++) {
            System.out.printf("%d\t", generator.next());
        }
        System.out.println();

        for (Integer i : new IterableFibonacciGenerator(10)) {
            System.out.printf("%d\t", i);
        }
        System.out.println();
    }
}
